package common

import (
	"Project/global"
	"Project/model/common/request"
	"Project/model/user"
	"Project/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
)

type LoginService struct{}

// Login 登录功能
func (login *LoginService) Login(loginRes request.LoginRes, c *gin.Context) (token string, err error) {
	//	判断用户是否存在
	oldPassword, authorID, userID := login.SelectLogin(loginRes.Phone, loginRes.Status)
	if oldPassword == "" {
		global.GVA_LOG.Info("用户不存在")
		return "", errors.New("用户不存在")
	}
	//	校验用户密码
	if !utils.BcryptCheck(loginRes.Password, oldPassword) {
		global.GVA_LOG.Info("密码错误")
		return "", errors.New("密码错误")
	}
	//  生成token
	token, err = login.CreateToken(authorID, userID)
	if err != nil {
		return
	}
	// 存储 uid:toke 到redis
	key := strconv.FormatInt(userID, 10)
	global.GVA_REDIS.Set(key, token, 0)

	return token, nil
}

// SelectLogin 选择表
func (login *LoginService) SelectLogin(phone, status string) (password string, authID, UserID int64) {
	if status == global.SaleUser {
		// 销售表
		var saleUser user.UserSale
		global.GVA_DB.Select([]string{"password", "auth_id", "sale_id"}).Find(&saleUser, "phone = ? and is_use = ?", phone, true)
		password = saleUser.Password
		authID = saleUser.AuthID
		UserID = saleUser.SaleID
	} else if status == global.Super {
		// 超级管理员
		superUser := user.UserSuper{}
		global.GVA_DB.Select([]string{"password", "auth_id", "super_id"}).Find(&superUser, "phone = ? and is_use = ?", phone, true)
		password = superUser.Password
		authID = superUser.AuthID
		UserID = superUser.SuperID
	} else if status == global.AreaUser {
		// 市区人员表
		areaUser := user.UserArea{}
		global.GVA_DB.Select([]string{"password", "auth_id", "user_id"}).Find(&areaUser, "phone = ? and is_use = ?", phone, true)
		password = areaUser.Password
		authID = areaUser.AuthID
		UserID = areaUser.UserID
	}
	return password, authID, UserID

}

func (login *LoginService) CreateToken(authID, userID int64) (token string, err error) {
	// 密钥
	secret := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)}
	claims := secret.CreateClaims(request.BaseClaims{
		ID:          userID,
		AuthorityId: authID,
	})
	// 创建token
	token, err = secret.CreateToken(claims)
	if err != nil {
		global.GVA_LOG.Error("获取token失败!", zap.Error(err))
		return "", errors.New("创建token失败")
	}
	return token, nil
}
